<template>
  <div>
    <div class="search-container">
      <el-input v-model="searchKeyword" placeholder="请输入商品标题进行搜索"></el-input>
      <el-button type="primary" @click="searchProducts">搜索</el-button>
    </div>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column fixed prop="id" label="商品ID" width="auto" />
      <!-- 假设数据中有 icon 字段表示商品图片，根据实际情况修改 -->
      <el-table-column prop="icon" label="商品图片" width="auto" #default="scope">
        <div class="demo-image__preview">
          <el-image style="width: 100px; height: 100px" :src="
                              scope.row.icon !== null ? scope.row.icon[0] : 'default-icon.png'
                            " @click="ifNull(scope.row)" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
            :preview-src-list="scope.row.iconList" :initial-index="4" fit="cover" />
        </div>
      </el-table-column>
      <!-- 假设数据中有 productTitle 字段表示商品介绍，根据实际情况修改 -->
      <el-table-column prop="productTitle" label="商品介绍" width="auto" />
      <!-- 假设数据中有 price 字段表示商品价格，根据实际情况修改 -->
      <el-table-column prop="price" label="商品价格" width="auto" />
      <el-table-column prop="brand" label="品牌" width="auto" />
      <el-table-column prop="upperHeight" label="鞋帮高度" width="auto" :filters="upperHeight" :filter-method="filterTag" />
      <el-table-column fixed="right" label="Operations" min-width="120">
        <template #default="scope">
          <el-dropdown trigger="click">
            <el-button link type="primary" size="small" @click="toggleDrawer(scope.row,'details');">
              详情
            </el-button>
          </el-dropdown>
          <el-button link type="primary" size="small" @click="toggleDrawer(scope.row,'updata')">
            修改
          </el-button>
          <el-button link type="primary" size="small" @click="handleClick3(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 详情信息抽屉 -->
    <el-drawer v-model="drawer.details" title="详细信息" size="20%">
      <productsDetail ref="productsDetailRef" :initial-data="currentRow" />
    </el-drawer>
  
    <!-- 修改商品对话框 -->
    <el-dialog v-model="drawer.updata" title="修改商品" width="1200" draggable @close="handleDialogClose">
      <updateProducts ref="updateProductsRef" :initial-data="currentRow" />
    </el-dialog>
  
    <div class="example-pagination-block">
      <el-pagination layout="prev, pager, next" :total="50" @current-change="handlePageChange"
        :current-page="currentPage" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRaw } from "vue";
import { useRouter } from "vue-router";
import { getProductList } from "../api/products";
import productsDetail from "./productsDetail.vue";
import updateProducts from "./updateProducts.vue";
// 假设这里有获取商品详情、更新商品、删除商品的 API 函数，实际中应根据你的需求引入
import {
  getProductDetail,
  updateProduct,
  deleteProduct,
} from "../api/products";
import { productsStore } from "../../store/user";

import { ElMessage } from "element-plus";

import { Products, upperHeight, drawerManage, stringOnArray } from "../ts/products";
const router = useRouter();
const proStore = productsStore();

const ifNull = (product: Products) => {
  console.log(product);
};

const productsDetailRef = ref(null);

// 定义 tableData 为响应式数据，类型为 Product[]
const tableData = ref<Products[]>([]);
// 定义 imageDataList 为图片的响应式数据
let imageDataList = reactive([]);
// 定义搜索关键词的响应式数据
const searchKeyword = ref("");
// 定义当前页码和每页数量
const currentPage = ref(1);
const pageSize = ref(10);

// 抽屉状态管理
const drawer = reactive(drawerManage);

// 当前操作的行数据
const currentRow = ref<typeof tableData.value[0] | null>(null)

// 切换抽屉状态
const toggleDrawer = (row: typeof tableData.value[0], type: 'details' | 'updata') => {
  currentRow.value = row;

  drawer[type] = !drawer[type];

  fetchData();
}

// 当弹窗被取消刷新数据
const handleDialogClose =()=> {
  fetchData();
}


const filterTag = (value: string, row: Products) => {
  return row.upperHeight === value
}


// 处理删除商品的点击事件
const handleClick3 = async (productId: number) => {
  try {
    const response = await deleteProduct(productId);
    // 假设接口返回的数据结构为 { success: true, code: 20000, message: '成功', data: { 相关删除结果数据... } }
    if (response.success) {
      ElMessage({
        message: "商品删除成功",
        type: "success",
      });
      // 重新获取商品列表
      await fetchData();
    } else {
      console.error("商品删除失败，错误信息:", response.message);
    }
  } catch (error) {
    console.error("商品删除出错:", error);
  }
};

// 获取商品基本信息
const fetchData = async () => {
  // 每次刷新初始化列表
  tableData.value = [];
  try {
    const data = await getProductList(
      currentPage.value,
      pageSize.value,
      searchKeyword.value
    );
    console.log(currentPage.value, pageSize.value, searchKeyword.value);
    // 假设接口返回的数据结构为 { success: true, code: 20000, message: '成功', data: { list: [...] } }
    if (data.success) {

      console.log(data.data.list);
      data.data.list.forEach((obj) => {
        tableData.value.push(stringOnArray(obj));
      });
    } else {
      console.error("数据请求失败，错误信息:", data.message);
    }
  } catch (error) {
    console.error("数据请求失败:", error);
  }
};

// 搜索商品的方法
const searchProducts = () => {
  currentPage.value = 1; // 搜索时重置页码为 1
  fetchData();
};

// 处理分页页码变化的事件
const handlePageChange = (page: number) => {
  currentPage.value = page;
  fetchData();
};

// 页面加载时调用获取数据的函数
fetchData();
</script>

<style scoped>
:deep(.el-dropdown) {
  height: 25px;
  margin-right: 12px;
}

.example-pagination-block {
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中，可根据需要调整为 align-items: flex-end 靠底部垂直居中 */
  /* align-items: flex-end; */
  margin-top: auto;
  /* 推到容器底部 */
}

.search-container {
  margin-bottom: 10px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.demo-image__error .image-slot {
  font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
</style>